<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">

    
      <link rel="icon" href="/favicon.png" />
    

    <title>
        
          CODE&#39;NOTE
        
    </title>

    <!-- Spectre.css framework -->
    <link href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre.min.css" rel="stylesheet">
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre-exp.min.css" rel="stylesheet">
    <link href="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre-icons.min.css" rel="stylesheet">

    <!-- theme css & js -->
    
<link rel="stylesheet" href="/css/book.css">

    
<script src="/js/book.js"></script>


    <!-- tocbot -->
    <script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/tocbot/4.18.2/tocbot.min.js"></script>
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/tocbot/4.18.2/tocbot.css" rel="stylesheet">
    
    <!-- katex -->    
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/KaTeX/0.15.2/katex.min.css" rel="stylesheet">

    
    
<script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/zooming/2.1.1/zooming.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const zooming = new Zooming()
    zooming.listen('.book-content img')
})
</script>

<meta name="generator" content="Hexo 6.1.0"></head>

<body>

<div class="book-container">
  <div class="book-sidebar">
    <div class="book-brand">
  <a href="/">
    <img src="/favicon.png">
    <span>CODE&#39;NOTE</span>
  </a>
</div>
    <div id="menu" class="book-menu hide">
  <h2 id="☘️-Home">☘️ <a href="/">Home</a></h2>
<h2 id="Go">Go</h2>
<ul>
<li><a href="/go/01%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA">0.1 开发环境搭建</a></li>
<li><a href="/go/02%E5%8F%98%E9%87%8F%E5%92%8C%E5%B8%B8%E9%87%8F">0.2 变量和常量</a></li>
<li><a href="/go/03%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B">0.3 基本数据类型</a></li>
<li><a href="/go/04%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E5%92%8C%E8%BF%90%E7%AE%97%E7%AC%A6">0.4 流程控制和运算符</a></li>
<li><a href="/go/05%E6%95%B0%E7%BB%84">0.5 数组</a></li>
<li><a href="/go/06%E5%88%87%E7%89%87">0.6 切片</a></li>
<li><a href="/go/07map">0.7 map</a></li>
<li><a href="/go/08%E5%87%BD%E6%95%B0">0.8 函数</a></li>
<li><a href="/go/09%E6%8C%87%E9%92%88">0.9 指针</a></li>
<li><a href="/go/10%E5%8F%8D%E5%B0%84">1.0 反射</a></li>
<li><a href="/go/11%E7%BB%93%E6%9E%84%E4%BD%93">1.1 结构体</a></li>
<li><a href="/go/12%E6%8E%A5%E5%8F%A3">1.2 接口</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/goroutine">1.3 goroutine</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/channel">1.4 channel</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/%E5%B9%B6%E5%8F%91%E5%AE%89%E5%85%A8%E5%92%8C%E9%94%81">1.5 并发安全和锁</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/%E5%8E%9F%E5%AD%90%E6%93%8D%E4%BD%9C">1.6 原子操作</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/GPM%E5%8E%9F%E7%90%86%E4%B8%8E%E8%B0%83%E5%BA%A6">1.7 GPM与调度分析</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/CSP%E5%B9%B6%E5%8F%91%E6%A8%A1%E5%9E%8B">1.8 CSP并发模型</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/fmt">标准库fmt</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/flag">标准库flag</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/time">标准库time</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/go_%E6%A0%87%E5%87%86%E5%BA%93log">标准库log</a></li>
</ul>
<!-- ##
## .NET

* [C# 入门基础合集](/dotnet/基础合集)
* [C# 面向对象](/dotnet/面向对象)
* [C# 数据结构](/dotnet/数据结构)
* [C# 泛型技术](/dotnet/泛型技术)
* [C# 反射技术](/dotnet/反射技术)
* [C# 多线程开发](/dotnet/多线程开发)
* [C# 多线程之线程同步技术](/dotnet/多线程之线程同步技术)
* [C# 委托和事件详解](/dotnet/委托和事件详解)
* [C# 并行编程](/dotnet/并行编程)
* [C# 异步编程](/dotnet/异步编程)
* [C# 值类型和引用类型内存分配](/dotnet/值类型和引用类型的内存分配)
* [1.1 DataProtection简介](/dotnet/1.1DataProtection简介)
* [1.2 DataProtection方法介绍](/dotnet/1.2DataProtection方法介绍)
* [1.3 落地实践及多环境调试](/dotnet/1.3落地实践及多环境调试)
* [1.4 UserSecrets](/dotnet/1.4UserSecrets)
* [1.5 数据保护方案](/dotnet/1.5基于DataProtection的数据保护方案)
* [1.6 集成AzureDevops](/dotnet/1.6方案实践及集成AzureDevops管道)


ELK Stack

* [ElastaticSearch入门](/elk/1.1ElastaticSearch入门)
* [ElastaticSearch配置](/elk/1.2ElastaticSearch配置)
* [使用Kibana操作ES](/elk/1.3使用Kibana操作ES)
 ## Docker

* [1.1 Docker概念及安装](/docker/1.1Docker概念及安装)
* [1.2 Docker镜像](/docker/1.2Docker镜像)
* [1.3 Docker容器](/docker/1.3Docker容器)
* [1.4 Docker仓库](/docker/1.4Docker仓库)
* [1.5 Docker数据管理](/docker/1.5Docker数据管理)
* [1.6 Docker容器四种网络模式](/docker/1.6Docker容器四种网络模式)
* [1.7 Docker高级网络配置](/docker/1.7Docker高级网络配置)
* [1.8 Dockerfile](/docker/1.8Dockerfile)
* [1.9 DockerCompose](/docker/1.9Docker三剑客之DockerCompose)
* [2.0 DockerMachine](/docker/2.0Docker三剑客之DockerMachine)
* [2.1 DockerSwarm](/docker/2.1Docker三剑客之DockerSwarm)
* [2.2 Docker常用命令](/docker/2.2Docker常用命令)
* [Portainer可视化面板](/docker/Portainer可视化面板)
* [1.6 Docker四种网络模式](/docker/1.6Docker容器网络模式)
* [1.7 Docker高级网络配置](/docker/1.7Docker高级网络配置)
* [1.8 Dockerfile](/docker/1.8Dockerfile)
* [1.9 DockerCompose](/docker/1.9DockerCompose)
* [2.0 DockerMachine](/docker/2.0DockerMachine)
* [2.1 DockerSwarm](/docker/2.1DockerSwarm)
* [2.2 Docker常用命令](/docker/2.2Docker常用命令)
* [Portainer可视化面板](/docker/Portainer可视化面板) 

## Linux

* [Centos安装](/linux/Centos安装)
* [Linux目录说明](/linux/Linux目录说明)
* [Centos网络配置](/linux/Centos网络配置)
* [Centos7升级gcc版本](/linux/Centos7升级gcc版本)
* [Linux常用命令](/linux/Linux常用命令)

## RabbitMQ

* [1.1 RabbitMQ概念及安装](/rabbitMq/1.1RabbitMQ概念及安装)
* [1.2 工作模式介绍](/rabbitMq/1.2工作模式介绍)
* [1.3 消息确认及持久化](/rabbitMq/1.3消息确认及持久化)
* [1.4 两种消费模式和QOS](/rabbitMq/1.4两种消费模式和QOS的实现)
* [1.5 Channel常见方法](/rabbitMq/1.5Channel常见方法)
* [1.6 RabbitMQ常用命令](/rabbitMq/1.6RabbitMQ常用命令)
* [1.7 RabbitMQ常见策略](/rabbitMq/1.7RabbitMQ常见策略)
* [1.8 RabbitMQ常见问题](/rabbitMq/1.8RabbitMQ常见问题)
* [1.9 RabbitMQ集群方案](/rabbitMq/1.9RabbitMQ集群方案)
* [客户端连接RabbitMQ](/rabbitMq/客户端连接RabbitMQ)

## Redis

* [1.1 NoSql概述](/redis/1.1NoSql概述)
* [1.2 Redis安装](/redis/1.2Redis安装)
* [1.3 Redis基本数据类型](/redis/1.3Redis基本数据类型)
* [1.4 Redis特殊数据类型](/redis/1.4Redis特殊数据类型)
* [1.5 Redis事务操作](/redis/1.5Redis事务操作)
* [1.6 Redis配置文件详解](/redis/1.6Redis配置文件详解)
* [1.7 Redis持久化](/redis/1.7Redis持久化)
* [1.8 Redis发布订阅](/redis/1.8Redis发布订阅)
* [1.9 Redis集群方案](/redis/1.9Redis集群方案)
* [1.10 Redis常见问题](/redis/1.10Redis常见问题)
* [客户端连接Redis](/redis/客户端连接Redis)
* [使用Docker搭建Redis集群](/redis/使用Docker搭建Redis集群)

## MicroService

* [1.1 微服务之项目搭建](/microservice/1.1微服务入门之项目搭建)
* [1.2 微服务之服务注册发现](/microservice/1.2微服务入门之服务注册与发现)
* [1.3 微服务之网关](/microservice/1.3微服务入门之网关)
* [1.4 微服务之事件总线](/microservice/1.4微服务入门之事件总线)
* [1.5 微服务之DockerCompose](/microservice/1.5微服务入门之DockerCompose)
* [Consul服务注册发现](/microservice/Consul服务注册发现)

## Test

* [单元测试](/test/单元测试)
* [集成测试](/test/集成测试)
* [压力测试k6](/test/压力测试k6)
* [自动化UI测试](/test/自动化UI测试) -->

</div>


<script src="/js/book-menu.js"></script>

  </div>

  <div class="sidebar-toggle" onclick="sidebar_toggle()" onmouseover="add_inner()" onmouseleave="remove_inner()">
  <div class="sidebar-toggle-inner"></div>
</div>

<script>
function add_inner() {
  let inner = document.querySelector('.sidebar-toggle-inner')
  inner.classList.add('show')  
}

function remove_inner() {
  let inner = document.querySelector('.sidebar-toggle-inner')
  inner.classList.remove('show')
}

function sidebar_toggle() {
    let sidebar_toggle = document.querySelector('.sidebar-toggle')
    let sidebar = document.querySelector('.book-sidebar')
    let content = document.querySelector('.off-canvas-content')
    if (sidebar_toggle.classList.contains('extend')) { // show
        sidebar_toggle.classList.remove('extend')
        sidebar.classList.remove('hide')
        content.classList.remove('extend')
    }
    else { // hide
        sidebar_toggle.classList.add('extend')
        sidebar.classList.add('hide')
        content.classList.add('extend')
    }
}
</script>

  <div class="off-canvas-content">
    <div class="columns">
      <div class="column col-10 col-lg-12">
        <div class="book-navbar">
          <!-- For Responsive Layout -->

<header class="navbar">
  <section class="navbar-section">
    <a onclick="open_sidebar()">
      <i class="icon icon-menu"></i>
    </a>
  </section>
</header>

        </div>
        <div class="book-content">
          <div class="book-post">
  <h1 id="自定义类型">自定义类型</h1>
<p>Go语言中有一些基本的数据类型，如<code>string</code>、<code>整型</code>、<code>浮点型</code>、<code>布尔</code>等数据类型， 使用<code>type</code>关键字来定义自定义类型。</p>
<p>自定义类型是定义了一个全新的类型。可以基于内置的基本类型定义，也可以通过 <code>struct</code> 定义。例如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 将MyInt定义为int类型</span></span><br><span class="line"><span class="keyword">type</span> MyInt <span class="type">int</span></span><br></pre></td></tr></table></figure>
<p>通过 <code>type</code> 关键字的定义，<code>MyInt</code> 就是一种新的类型，具有 <code>int</code> 的特性。</p>
<h1 id="类型别名">类型别名</h1>
<p>类型别名是<code>Go1.9</code>版本添加的新功能。类型别名规定：<code>TypeAlias</code> 只是Type的别名，本质上TypeAlias与Type是同一个类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> TypeAlias = Type</span><br></pre></td></tr></table></figure>
<p>之前见过的<code>rune</code>和<code>byte</code>就是类型别名，定义如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="type">byte</span> = <span class="type">uint8</span></span><br><span class="line"><span class="keyword">type</span> <span class="type">rune</span> = <span class="type">int32</span></span><br></pre></td></tr></table></figure>
<h1 id="自定义类型-类型别名区别">自定义类型/类型别名区别</h1>
<p>类型别名与类型定义表面上看只有一个等号的差异，通过下面的这段代码来理解它们之间的区别：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 类型定义</span></span><br><span class="line"><span class="keyword">type</span> NewInt <span class="type">int</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 类型别名</span></span><br><span class="line"><span class="keyword">type</span> MyInt = <span class="type">int</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> a NewInt</span><br><span class="line">	<span class="keyword">var</span> b MyInt</span><br><span class="line">	</span><br><span class="line">	fmt.Printf(<span class="string">&quot;type of a:%T\n&quot;</span>, a) <span class="comment">// type of a:main.NewInt</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;type of b:%T\n&quot;</span>, b) <span class="comment">// type of b:int</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>结果显示a的类型是 <code>main.NewInt</code>，表示main包下定义的<code>NewInt</code>类型。b的类型是<code>int</code>。<code>MyInt</code>类型只会在代码中存在，编译完成时并不会有<code>MyInt</code>类型。</p>
<h1 id="结构定义">结构定义</h1>
<p>Go语言的结构体（struct）和其他语言的类（class）有同等的地位，但Go语言放弃了大量面向对象特性，只保留了组合（composition）这个最基础的特性。Go语言中可以通过 <code>struct</code> 来实现面向对象。</p>
<p>使用 <code>type</code> 和 <code>struct</code> 关键字来定义结构体，具体代码格式如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> 类型名 <span class="keyword">struct</span> &#123;</span><br><span class="line">    字段名 字段类型</span><br><span class="line">    字段名 字段类型</span><br><span class="line">    …</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中：</p>
<ul>
<li>类型名：标识自定义结构体的名称。在同一个包内不能重复</li>
<li>字段名：表示结构体字段名。结构体中的字段名必须唯一</li>
<li>字段类型：表示结构体字段的具体类型</li>
</ul>
<p>比如：定义一个表示矩形的结构</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Rect <span class="keyword">struct</span> &#123;</span><br><span class="line">	width  <span class="type">float64</span></span><br><span class="line">	height <span class="type">float64</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>同样类型的字段也可以写在一行，看起来更简洁</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Rect <span class="keyword">struct</span> &#123;</span><br><span class="line">	width, height <span class="type">float64</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>语言内置的基础数据类型是用来描述一个值的，而结构体是用来描述一组值的。本质上是一种聚合型的数据类型。</p>
<h1 id="结构实例化">结构实例化</h1>
<p><strong>最简单的实例化方式</strong>：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> rect Rect</span><br><span class="line">fmt.Printf(<span class="string">&quot;%p %T \n&quot;</span>, &amp;rect, rect)</span><br><span class="line">rect.height = <span class="number">13.4</span></span><br><span class="line">rect.width = <span class="number">21.</span></span><br><span class="line">fmt.Printf(<span class="string">&quot;%p %T \n&quot;</span>, &amp;rect, rect)</span><br><span class="line">fmt.Println(rect.height, rect.width)</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">0xc0000120a0 main.Rect </span><br><span class="line">0xc0000120a0 main.Rect </span><br><span class="line">13.4 21</span><br></pre></td></tr></table></figure>
<p>因为结构是值类型，所以定义结构体类型变量就会分配内存，如果不给结构体中的字段赋值，默认就会是该类型的零值。而后可以通过<code>.</code>来访问结构体的字段</p>
<p><strong>创建指针类型结构</strong>：</p>
<p>通过使用 <code>new</code> 关键字对结构体进行实例化，得到的是结构体的内存地址。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> rect = <span class="built_in">new</span>(Rect)</span><br><span class="line">   <span class="comment">// Go语言中支持对结构体指针直接使用.来访问结构体的成员</span></span><br><span class="line">rect.height = <span class="number">13.4</span></span><br><span class="line">rect.width = <span class="number">21.4</span></span><br><span class="line">   <span class="comment">// 这里因为使用new()返回的已经是指针类型,所以打印输出时不需要加&amp;取址</span></span><br><span class="line">fmt.Printf(<span class="string">&quot;%T %p\n&quot;</span>, rect, rect)</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">*main.Rect 0xc0000aa070</span><br></pre></td></tr></table></figure>
<p><strong>使用结构体的地址实例化</strong>：</p>
<p>使用<code>&amp;</code>对结构体进行取地址操作相当于对该结构体类型进行了一次<code>new</code>实例化操作。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> rect = &amp;Rect&#123;&#125;</span><br><span class="line">rect.height = <span class="number">13.4</span></span><br><span class="line">rect.width = <span class="number">21.4</span></span><br><span class="line">fmt.Printf(<span class="string">&quot;%T %p\n&quot;</span>, rect, rect)</span><br></pre></td></tr></table></figure>
<h1 id="结构初始化">结构初始化</h1>
<p><strong>默认</strong>：没有初始化的结构体，其成员变量都是对应其类型的零值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> rect Rect</span><br><span class="line">fmt.Printf(<span class="string">&quot;%#v \n&quot;</span>, rect)</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">main.Rect&#123;width:0, height:0&#125;</span><br></pre></td></tr></table></figure>
<p><strong>使用键值对初始化</strong>：</p>
<p>使用键值对初始化时，键对应结构体的字段，值对应该字段的初始值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">rect := Rect&#123;width: <span class="number">10.5</span>, height: <span class="number">3.5</span>&#125;</span><br><span class="line">fmt.Printf(<span class="string">&quot;%#v \n&quot;</span>, rect)</span><br></pre></td></tr></table></figure>
<p>也可以对结构体指针进行键值对初始化，比如：</p>
<figure class="highlight django"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="language-xml">// 对结构体指针进行键值初始化</span></span><br><span class="line"><span class="language-xml">rect2 := &amp;Rect&#123;width: 10.5, height: 3.5&#125;</span></span><br><span class="line"><span class="language-xml">fmt.Printf(&quot;%#v \n&quot;, rect2)</span></span><br></pre></td></tr></table></figure>
<p>如果字段没有初始值,可以省略，那么被省略的值就是该字段的零值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 如果字段没有初始值,可以省略,那么被省略的值就是该字段的零值</span></span><br><span class="line">rect3 := Rect&#123;width: <span class="number">100.0</span>&#125;</span><br><span class="line">fmt.Printf(<span class="string">&quot;%#v \n&quot;</span>, rect3)	</span><br></pre></td></tr></table></figure>
<p><strong>使用值的列表初始化</strong>：</p>
<p>初始化结构体的时候可以简写，也就是初始化的时候不写键，直接写值：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">rect := Rect&#123;<span class="number">10.5</span>, <span class="number">3.5</span>&#125;</span><br><span class="line">fmt.Printf(<span class="string">&quot;%#v \n&quot;</span>, rect)</span><br><span class="line"></span><br><span class="line">rect2 := &amp;Rect&#123;<span class="number">10.5</span>, <span class="number">3.5</span>&#125;</span><br><span class="line">fmt.Printf(<span class="string">&quot;%#v \n&quot;</span>, rect2)</span><br></pre></td></tr></table></figure>
<p>使用这种格式初始化时，需要注意：</p>
<ol>
<li>必须初始化结构体的所有字段</li>
<li>初始值的填充顺序必须与字段在结构体中的声明顺序一致</li>
<li>该方式不能和键值初始化方式混用</li>
</ol>
<h1 id="匿名结构体">匿名结构体</h1>
<p>在定义一些临时数据结构等场景下可以使用匿名结构体。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 匿名结构体</span></span><br><span class="line"><span class="keyword">var</span> user <span class="keyword">struct</span> &#123;</span><br><span class="line">	name <span class="type">string</span></span><br><span class="line">	age  <span class="type">int</span></span><br><span class="line">&#125;</span><br><span class="line">user.name = <span class="string">&quot;wangpengliang&quot;</span></span><br><span class="line">user.age = <span class="number">18</span></span><br><span class="line">fmt.Printf(<span class="string">&quot;%v \n&quot;</span>, user)</span><br></pre></td></tr></table></figure>
<h1 id="空结构体">空结构体</h1>
<p>空结构体不占用内存空间。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a <span class="keyword">struct</span>&#123;&#125;</span><br><span class="line">fmt.Println(unsafe.Sizeof(a)) <span class="comment">// 0</span></span><br></pre></td></tr></table></figure>
<h1 id="结构体内存布局">结构体内存布局</h1>
<p>结构体占用一块连续的内存。</p>
<p>TODO：<a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000017527311?utm_campaign=studygolang.com&amp;utm_medium=studygolang.com&amp;utm_source=studygolang.com">在 Go 中恰到好处的内存对齐</a></p>
<h1 id="构造函数">构造函数</h1>
<p>Go语言的结构体没有构造函数，可以自己实现。 因为<code>struct</code>是值类型，如果结构体比较复杂的话，值拷贝性能开销会比较大，所以构造函数返回的是结构体指针类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 如果不初始化,字段值为类型零值</span></span><br><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;</span><br><span class="line">	name    <span class="type">string</span></span><br><span class="line">	age     <span class="type">int</span></span><br><span class="line">	address <span class="type">string</span></span><br><span class="line">	hobby   []<span class="type">string</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 第一种方式,使用指定值初始化结构体,返回指针类型</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">NewPerson</span><span class="params">(name, address <span class="type">string</span>, age <span class="type">int</span>, hobby []<span class="type">string</span>)</span></span> *Person &#123;</span><br><span class="line">	instance := <span class="built_in">new</span>(Person)</span><br><span class="line">	instance.name = name</span><br><span class="line">	instance.address = address</span><br><span class="line">	instance.age = age</span><br><span class="line">	instance.hobby = hobby</span><br><span class="line">	<span class="keyword">return</span> instance</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 第二种方式,使用&amp;初始化结构体,返回指针类型</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">NewPerson2</span><span class="params">(name, address <span class="type">string</span>, age <span class="type">int</span>)</span></span> *Person &#123;</span><br><span class="line">	<span class="keyword">return</span> &amp;Person&#123;</span><br><span class="line">		name:    name,</span><br><span class="line">		address: address,</span><br><span class="line">		age:     age,</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Go中不支持函数重载，但是可以通过两个名称不同的构造函数来模拟实现构造函数重载。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a := NewPerson(<span class="string">&quot;wangpengliang&quot;</span>, <span class="string">&quot;beijing&quot;</span>, <span class="number">18</span>, []<span class="type">string</span>&#123;<span class="string">&quot;java&quot;</span>, <span class="string">&quot;go&quot;</span>&#125;)</span><br><span class="line">fmt.Println(a)</span><br><span class="line">b := NewPerson2(<span class="string">&quot;wangpengliang&quot;</span>, <span class="string">&quot;beijing&quot;</span>, <span class="number">18</span>)</span><br><span class="line">fmt.Println(b)	</span><br></pre></td></tr></table></figure>
<h1 id="方法和接收者">方法和接收者</h1>
<p>Go语言中的<code>方法（Method）</code>是一种作用于特定类型变量的函数。这种特定类型变量叫做<code>接收者（Receiver）</code>方法的定义格式如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(接收者变量 接收者类型)</span></span> 方法名(参数列表) (返回参数) &#123;</span><br><span class="line">    函数体</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中：</p>
<ul>
<li>接收者变量：接收者中的参数变量名在命名时，官方建议使用接收者类型名称首字母的小写，而不是<code>self</code>、<code>this</code>之类的命名。例如，<code>Person</code>类型的接收者变量应该命名为 <code>p</code>，<code>Connector</code>类型的接收者变量应该命名为<code>c</code>等</li>
<li>接收者类型：接收者类型和参数类似，可以是指针类型和非指针类型</li>
<li>方法名、参数列表、返回参数：具体格式与函数定义相同</li>
</ul>
<p>简单理解：因为Go语言中没有Class的概念，所以不存在实例化一个类调用其中某个方法这种做法，Go语言中的方法其实就是给指定结构添加方法。比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 给结构体Person定义方法,所谓方法在go中就是定义了接受者的函数</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p Person)</span></span> say1() &#123;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;name: %s,age：%d  \n&quot;</span>, p.name, p.age)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p Person)</span></span> addAge1() &#123;</span><br><span class="line">	p.age = p.age + <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>方法与函数的区别在于：<strong>函数不属于任何类型，方法属于特定的类型</strong>。</p>
<h2 id="值类型的接收者">值类型的接收者</h2>
<p>当方法作用于值类型接收者时，Go语言会在代码运行时将接收者的值复制一份。在值类型接收者的方法中可以获取接收者的成员值，但修改操作只是针对副本，无法修改接收者变量本身。比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 给结构体Person定义方法,所谓方法在go中就是定义了接受者的函数</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p Person)</span></span> say1() &#123;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;name: %s,age：%d  \n&quot;</span>, p.name, p.age)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p Person)</span></span> addAge1() &#123;</span><br><span class="line">	p.age = p.age + <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p1 Person = Person&#123;<span class="string">&quot;zhansan&quot;</span>, <span class="number">16</span>, <span class="string">&quot;beijing&quot;</span>, []<span class="type">string</span>&#123;&#125;&#125;</span><br><span class="line">p1.addAge1()</span><br><span class="line">p1.say1()</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> p2 *Person = &amp;Person&#123;<span class="string">&quot;lisi&quot;</span>, <span class="number">16</span>, <span class="string">&quot;shanghai&quot;</span>, []<span class="type">string</span>&#123;&#125;&#125;</span><br><span class="line">p2.addAge1()</span><br><span class="line">p2.say1()</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">name: zhansan,age：16  </span><br><span class="line">name: lisi,age：16   </span><br></pre></td></tr></table></figure>
<h2 id="指针类型的接收者">指针类型的接收者</h2>
<p>指针类型的接收者由一个结构体的指针组成，由于指针的特性，调用方法时修改接收者指针的任意成员变量，在方法结束后，修改都是有效的。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p *Person)</span></span> say2() &#123;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;name: %s,age：%d  \n&quot;</span>, p.name, p.age)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p *Person)</span></span> addAge2() &#123;</span><br><span class="line">	p.age = p.age + <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p3 Person = Person&#123;<span class="string">&quot;zhansan&quot;</span>, <span class="number">16</span>, <span class="string">&quot;beijing&quot;</span>, []<span class="type">string</span>&#123;&#125;&#125;</span><br><span class="line">p3.addAge2()</span><br><span class="line">p3.say2()</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> p4 *Person = &amp;Person&#123;<span class="string">&quot;lisi&quot;</span>, <span class="number">16</span>, <span class="string">&quot;beijing&quot;</span>, []<span class="type">string</span>&#123;&#125;&#125;</span><br><span class="line">p4.addAge2()</span><br><span class="line">p4.say2()</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">name: zhansan,age：17  </span><br><span class="line">name: lisi,age：17  </span><br></pre></td></tr></table></figure>
<p><strong>什么时候使用指针类型接收?</strong></p>
<ol>
<li>需要修改接收者中的值</li>
<li>接收者是拷贝代价比较大的大对象</li>
<li>保证一致性，如果有某个方法使用了指针接收者，那么其他的方法也应该使用指针接收者。</li>
</ol>
<h1 id="任意类型添加方法">任意类型添加方法</h1>
<p>Go语言中，接收者的类型可以是任何类型，不仅仅是结构体，任何类型都可以拥有方法。比如：基于内置的<code>int</code>类型使用 type 关键字可以定义新的自定义类型，然后为自定义类型添加方法。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// MyInt 将int定义为自定义MyInt类型</span></span><br><span class="line"><span class="keyword">type</span> MyInt <span class="type">int</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// SayHello 为MyInt添加一个SayHello的方法</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(m MyInt)</span></span> SayHello() &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;Hello, 我是一个int。&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> m1 MyInt</span><br><span class="line">	m1.SayHello() <span class="comment">//Hello, 我是一个int。</span></span><br><span class="line">	m1 = <span class="number">100</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;%#v  %T\n&quot;</span>, m1, m1) <span class="comment">//100  main.MyInt</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>注意事项：</strong> 非本地类型不能定义方法，不能给别的包的类型定义方法。</p>
<h1 id="结构体的匿名字段">结构体的匿名字段</h1>
<p>结构体允许其成员字段在声明时没有字段名而只有类型，这种没有名字的字段就称为匿名字段。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 匿名字段的说法并不代表没有字段名，而是默认会采用类型名作为字段名，结构体要求字段名称必须唯一，因此一个结构体中同种类型的匿名字段只能有一个</span></span><br><span class="line"><span class="keyword">type</span> Book <span class="keyword">struct</span> &#123;</span><br><span class="line">	<span class="type">string</span></span><br><span class="line">	<span class="type">float64</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	book := Book&#123;</span><br><span class="line">		<span class="string">&quot;go语言编程&quot;</span>,</span><br><span class="line">		<span class="number">100.00</span>,</span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;%#v\n&quot;</span>, book)              <span class="comment">// main.Book&#123;string:&quot;go语言编程&quot;, float64:100&#125;</span></span><br><span class="line">	fmt.Println(book.<span class="type">string</span>, book.<span class="type">float64</span>) <span class="comment">//北京 go语言编程 100</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>注意</strong>：这里匿名字段的说法并不代表没有字段名，而是默认会采用类型名作为字段名，结构体要求字段名称必须唯一，因此一个结构体中同种类型的匿名字段只能有一个。</p>
<h1 id="嵌套结构体">嵌套结构体</h1>
<p>一个结构体中可以嵌套包含另一个结构体或结构体指针，比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 地址结构体</span></span><br><span class="line"><span class="keyword">type</span> Address <span class="keyword">struct</span> &#123;</span><br><span class="line">	Province <span class="type">string</span></span><br><span class="line">	City     <span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 用户结构体</span></span><br><span class="line"><span class="keyword">type</span> User <span class="keyword">struct</span> &#123;</span><br><span class="line">	Name    <span class="type">string</span></span><br><span class="line">	Gender  <span class="type">string</span></span><br><span class="line">	Address Address</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	user := User&#123;</span><br><span class="line">		Name:   <span class="string">&quot;wangpengliang&quot;</span>,</span><br><span class="line">		Gender: <span class="string">&quot;男&quot;</span>,</span><br><span class="line">		Address: Address&#123;</span><br><span class="line">			Province: <span class="string">&quot;山西&quot;</span>,</span><br><span class="line">			City:     <span class="string">&quot;长治&quot;</span>,</span><br><span class="line">		&#125;,</span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;user=%#v\n&quot;</span>, user)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">user=main.User&#123;Name:<span class="string">&quot;wangpengliang&quot;</span>, Gender:<span class="string">&quot;男&quot;</span>, Address:main.Address&#123;Province:<span class="string">&quot;山西&quot;</span>, City:<span class="string">&quot;长治&quot;</span>&#125;&#125;</span><br></pre></td></tr></table></figure>
<h1 id="嵌套匿名字段">嵌套匿名字段</h1>
<p>上面user结构体中嵌套的<code>Address</code>结构体也可以采用匿名字段的方式，匿名字段默认使用类型名作为字段名。比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 地址结构体</span></span><br><span class="line"><span class="keyword">type</span> Address <span class="keyword">struct</span> &#123;</span><br><span class="line">	province <span class="type">string</span></span><br><span class="line">	city     <span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 用户结构体</span></span><br><span class="line"><span class="keyword">type</span> User <span class="keyword">struct</span> &#123;</span><br><span class="line">	name    <span class="type">string</span></span><br><span class="line">	gender  <span class="type">string</span></span><br><span class="line">	address Address <span class="comment">// 该字段为具名字段</span></span><br><span class="line">	Address         <span class="comment">// 嵌套的Address结构体也可以采用匿名字段的方式</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	user := User&#123;</span><br><span class="line">		name:   <span class="string">&quot;wangpengliang&quot;</span>,</span><br><span class="line">		gender: <span class="string">&quot;男&quot;</span>,</span><br><span class="line">		address: Address&#123;</span><br><span class="line">			province: <span class="string">&quot;山西&quot;</span>,</span><br><span class="line">			city:     <span class="string">&quot;长治&quot;</span>,</span><br><span class="line">		&#125;,</span><br><span class="line">		Address: Address&#123;</span><br><span class="line">			province: <span class="string">&quot;北京&quot;</span>,</span><br><span class="line">			city:     <span class="string">&quot;北京&quot;</span>,</span><br><span class="line">		&#125;,</span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;user=%#v\n&quot;</span>, user)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">user=main.User&#123;name:<span class="string">&quot;wangpengliang&quot;</span>, gender:<span class="string">&quot;男&quot;</span>, address:main.Address&#123;province:<span class="string">&quot;山西&quot;</span>, city:<span class="string">&quot;长治&quot;</span>&#125;, Address:main.Address&#123;province:<span class="string">&quot;北京&quot;</span>, city:<span class="string">&quot;北京&quot;</span>&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>当访问结构体成员时会先在结构体中查找该字段，找不到再去嵌套的匿名字段中查找。</p>
<h1 id="嵌套结构体字段名冲突">嵌套结构体字段名冲突</h1>
<p>嵌套结构体内部可能存在相同的字段名。这种情况下为了避免歧义需要通过指定具体的内嵌结构体字段名。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 地址结构体</span></span><br><span class="line"><span class="keyword">type</span> Address <span class="keyword">struct</span> &#123;</span><br><span class="line">	province   <span class="type">string</span></span><br><span class="line">	city       <span class="type">string</span></span><br><span class="line">	createTime <span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 邮箱结构体</span></span><br><span class="line"><span class="keyword">type</span> Email <span class="keyword">struct</span> &#123;</span><br><span class="line">	account    <span class="type">string</span></span><br><span class="line">	createTime <span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 用户结构体</span></span><br><span class="line"><span class="keyword">type</span> User <span class="keyword">struct</span> &#123;</span><br><span class="line">	name    <span class="type">string</span></span><br><span class="line">	gender  <span class="type">string</span></span><br><span class="line">	address Address <span class="comment">// 该字段为具名字段</span></span><br><span class="line">	Address         <span class="comment">// 嵌套的Address结构体也可以采用匿名字段的方式</span></span><br><span class="line">	Email</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 具名字段赋值</span></span><br><span class="line">	user := User&#123;</span><br><span class="line">		name:   <span class="string">&quot;wangpengliang&quot;</span>,</span><br><span class="line">		gender: <span class="string">&quot;男&quot;</span>,</span><br><span class="line">		address: Address&#123;</span><br><span class="line">			province: <span class="string">&quot;山西&quot;</span>,</span><br><span class="line">			city:     <span class="string">&quot;长治&quot;</span>,</span><br><span class="line">		&#125;,</span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;user=%#v\n&quot;</span>, user)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 匿名字段</span></span><br><span class="line">	user1 := User&#123;</span><br><span class="line">		name:   <span class="string">&quot;wangpengliang&quot;</span>,</span><br><span class="line">		gender: <span class="string">&quot;男&quot;</span>,</span><br><span class="line">		Address: Address&#123;</span><br><span class="line">			province: <span class="string">&quot;山西&quot;</span>,</span><br><span class="line">			city:     <span class="string">&quot;长治&quot;</span>,</span><br><span class="line">		&#125;,</span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;user1=%#v\n&quot;</span>, user1)</span><br><span class="line"></span><br><span class="line">	<span class="keyword">var</span> user2 User</span><br><span class="line">	user2.name = <span class="string">&quot;wangpengliang&quot;</span></span><br><span class="line">	user2.gender = <span class="string">&quot;男&quot;</span></span><br><span class="line">	<span class="comment">// user2.createTime = &quot;2019&quot; //ambiguous selector user2.createTime</span></span><br><span class="line">	user2.Address.createTime = <span class="string">&quot;2000&quot;</span> <span class="comment">//指定Address结构体中的createTime</span></span><br><span class="line">	user2.Email.createTime = <span class="string">&quot;2000&quot;</span>   <span class="comment">//指定Email结构体中的createTime</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">user=main.User&#123;name:<span class="string">&quot;wangpengliang&quot;</span>, gender:<span class="string">&quot;男&quot;</span>, address:main.Address&#123;province:<span class="string">&quot;山西&quot;</span>, city:<span class="string">&quot;长治&quot;</span>, createTime:<span class="string">&quot;&quot;</span>&#125;, Address:main.Address&#123;province:<span class="string">&quot;&quot;</span>, city:<span class="string">&quot;&quot;</span>, createTime:<span class="string">&quot;&quot;</span>&#125;, Email:main.Email&#123;account:<span class="string">&quot;&quot;</span>, createTime:<span class="string">&quot;&quot;</span>&#125;&#125;</span><br><span class="line">user=main.User&#123;name:<span class="string">&quot;wangpengliang&quot;</span>, gender:<span class="string">&quot;男&quot;</span>, address:main.Address&#123;province:<span class="string">&quot;&quot;</span>, city:<span class="string">&quot;&quot;</span>, createTime:<span class="string">&quot;&quot;</span>&#125;, Address:main.Address&#123;province:<span class="string">&quot;山西&quot;</span>, city:<span class="string">&quot;长治&quot;</span>, createTime:<span class="string">&quot;&quot;</span>&#125;, Email:main.Email&#123;account:<span class="string">&quot;&quot;</span>, createTime:<span class="string">&quot;&quot;</span>&#125;&#125;</span><br></pre></td></tr></table></figure>
<h1 id="结构体字段可见性">结构体字段可见性</h1>
<p>结构体中字段大写开头表示可公开访问，小写表示私有（仅在定义当前结构体的包中可访问）。</p>
<h1 id="结构体与JSON序列化">结构体与JSON序列化</h1>
<p><code>JSON(JavaScript Object Notation)</code>  是一种轻量级的数据交换格式。易于阅读和编写。同时也易于机器解析和生成。JSON键值对是用来保存JS对象的一种方式，键/值对组合中的键名写在前面并用双引号<code>&quot;&quot;</code>包裹，使用冒号<code>:</code>分隔，然后紧接着值；多个键值之间使用英文<code>,</code>分隔。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Student</span></span><br><span class="line"><span class="keyword">type</span> Student <span class="keyword">struct</span> &#123;</span><br><span class="line">	ID     <span class="type">int</span></span><br><span class="line">	Gender <span class="type">string</span></span><br><span class="line">	Name   <span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Class</span></span><br><span class="line"><span class="keyword">type</span> Class <span class="keyword">struct</span> &#123;</span><br><span class="line">	Title    <span class="type">string</span></span><br><span class="line">	Students []*Student</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">jsonSerializeTest</span><span class="params">()</span></span> &#123;</span><br><span class="line">	c := &amp;Class&#123;</span><br><span class="line">		Title:    <span class="string">&quot;101&quot;</span>,</span><br><span class="line">		Students: <span class="built_in">make</span>([]*Student, <span class="number">0</span>, <span class="number">200</span>),</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="number">10</span>; i++ &#123;</span><br><span class="line">		stu := &amp;Student&#123;</span><br><span class="line">			Name:   fmt.Sprintf(<span class="string">&quot;stu%02d&quot;</span>, i),</span><br><span class="line">			Gender: <span class="string">&quot;男&quot;</span>,</span><br><span class="line">			ID:     i,</span><br><span class="line">		&#125;</span><br><span class="line">		c.Students = <span class="built_in">append</span>(c.Students, stu)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// JSON序列化：结构体--&gt;JSON格式的字符串</span></span><br><span class="line">	data, err := json.Marshal(c)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(<span class="string">&quot;json marshal failed&quot;</span>)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;json:%s\n&quot;</span>, data)</span><br><span class="line">	<span class="comment">//JSON反序列化：JSON格式的字符串--&gt;结构体</span></span><br><span class="line">	str := <span class="string">`&#123;&quot;Title&quot;:&quot;101&quot;,&quot;Students&quot;:[&#123;&quot;ID&quot;:0,&quot;Gender&quot;:&quot;男&quot;,&quot;Name&quot;:&quot;stu00&quot;&#125;,&#123;&quot;ID&quot;:1,&quot;Gender&quot;:&quot;男&quot;,&quot;Name&quot;:&quot;stu01&quot;&#125;,&#123;&quot;ID&quot;:2,&quot;Gender&quot;:&quot;男&quot;,&quot;Name&quot;:&quot;stu02&quot;&#125;,&#123;&quot;ID&quot;:3,&quot;Gender&quot;:&quot;男&quot;,&quot;Name&quot;:&quot;stu03&quot;&#125;,&#123;&quot;ID&quot;:4,&quot;Gender&quot;:&quot;男&quot;,&quot;Name&quot;:&quot;stu04&quot;&#125;,&#123;&quot;ID&quot;:5,&quot;Gender&quot;:&quot;男&quot;,&quot;Name&quot;:&quot;stu05&quot;&#125;,&#123;&quot;ID&quot;:6,&quot;Gender&quot;:&quot;男&quot;,&quot;Name&quot;:&quot;stu06&quot;&#125;,&#123;&quot;ID&quot;:7,&quot;Gender&quot;:&quot;男&quot;,&quot;Name&quot;:&quot;stu07&quot;&#125;,&#123;&quot;ID&quot;:8,&quot;Gender&quot;:&quot;男&quot;,&quot;Name&quot;:&quot;stu08&quot;&#125;,&#123;&quot;ID&quot;:9,&quot;Gender&quot;:&quot;男&quot;,&quot;Name&quot;:&quot;stu09&quot;&#125;]&#125;`</span></span><br><span class="line">	c1 := &amp;Class&#123;&#125;</span><br><span class="line">	err = json.Unmarshal([]<span class="type">byte</span>(str), c1)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(<span class="string">&quot;json unmarshal failed!&quot;</span>)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;%#v\n&quot;</span>, c1)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="结构体标签（Tag）">结构体标签（Tag）</h1>
<p><code>Tag</code>是结构体的元信息，可以在运行时通过反射读取出来。 <code>Tag</code>在结构体字段的后方定义，由一对<strong>反引号</strong>包裹起来，格式如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">`key1:<span class="string">&quot;value1&quot;</span> key2:<span class="string">&quot;value2&quot;</span>`</span><br></pre></td></tr></table></figure>
<p>结构体tag由一个或多个键值对组成。键与值使用冒号分隔，值用双引号括起来。同一个结构体字段可以设置多个键值对tag，不同的键值对之间使用空格分隔。</p>
<p><strong>注意事项：</strong> 为结构体编写<code>Tag</code>时，必须严格遵守键值对的规则。结构体标签的解析代码的容错能力很差，一旦格式写错，编译和运行时都不会提示任何错误，通过反射也无法正确取值。例如不要在key和value之间添加空格。</p>
<p>Go 中标签最常见的用途比如 <strong><a href="https://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Marshalling_(computer_science)">marshalling</a></strong>。看一下来自 JSON 包的函数 <strong><a href="https://link.zhihu.com/?target=https%3A//golang.org/pkg/encoding/json/%23Marshal">Marshal</a></strong> 如何使用它（<strong><a href="https://link.zhihu.com/?target=https%3A//play.golang.org/p/C1hAMXTKPM_S">源代码</a></strong>）：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">import (</span><br><span class="line">    &quot;encoding/json&quot;</span><br><span class="line">    &quot;fmt&quot;</span><br><span class="line">)</span><br><span class="line">func main() &#123;</span><br><span class="line">    type T struct &#123;</span><br><span class="line">       F1 int `json:&quot;f_1&quot;`</span><br><span class="line">       F2 int `json:&quot;f_2,omitempty&quot;`</span><br><span class="line">       F3 int `json:&quot;f_3,omitempty&quot;`</span><br><span class="line">       F4 int `json:&quot;-&quot;`</span><br><span class="line">    &#125;</span><br><span class="line">    t := T&#123;1, 0, 2, 3&#125;</span><br><span class="line">    b, err := JSON.Marshal(t)</span><br><span class="line">    if err != nil &#123;</span><br><span class="line">        panic(err)</span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Printf(&quot;%s\n&quot;, b) // &#123;&quot;f_1&quot;:1,&quot;f_3&quot;:2&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>xml 包也利用了标签 - <a href="https://link.zhihu.com/?target=https%3A//golang.org/pkg/encoding/xml/%23MarshalIndent">https://golang.org/pkg/encoding/xml/#MarshalIndent</a>.</p>
<p><strong>ORM</strong></p>
<p>像 GORM 这样的对象关系映射工具，也广泛使用标签 - <strong><a href="https://link.zhihu.com/?target=https%3A//github.com/jinzhu/gorm/blob/58e34726dfc069b558038efbaa25555f182d1f7a/multi_primary_keys_test.go%23L10">例子</a></strong>.</p>
<p><strong>摘要数据（Digesting forms data）</strong></p>
<p><a href="https://link.zhihu.com/?target=https%3A//godoc.org/github.com/gorilla/schema">https://godoc.org/github.com/gorilla/schema</a></p>
<p><strong>其他（Other）</strong></p>
<p>标签的更多潜在用例，如配置管理，结构的默认值，验证，命令行参数描述等（<strong><a href="https://link.zhihu.com/?target=https%3A//github.com/golang/go/wiki/Well-known-struct-tags">众所周知的结构标记列表</a></strong>）。</p>
<h1 id="练习题一">练习题一</h1>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">exercises01Test</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="built_in">make</span> := <span class="built_in">make</span>(<span class="keyword">map</span>[<span class="type">int</span>]*<span class="type">int</span>)</span><br><span class="line">	slice := []<span class="type">int</span>&#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;</span><br><span class="line">	<span class="keyword">for</span> index, value := <span class="keyword">range</span> slice &#123;</span><br><span class="line">		<span class="built_in">make</span>[index] = &amp;value</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span> k, v := <span class="keyword">range</span> <span class="built_in">make</span> &#123;</span><br><span class="line">		fmt.Println(k, <span class="string">&quot;=&gt;&quot;</span>, *v)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">0 =&gt; 3</span><br><span class="line">1 =&gt; 3</span><br><span class="line">2 =&gt; 3</span><br><span class="line">3 =&gt; 3</span><br></pre></td></tr></table></figure>
<p>思考：这里输出map的value为什么都是3?</p>
<p>调整代码：输出指针地址</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> index, value := <span class="keyword">range</span> slice &#123;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;%p \n&quot;</span>, &amp;value)</span><br><span class="line">	<span class="built_in">make</span>[index] = &amp;value</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">0xc000012088 </span><br><span class="line">0xc000012088 </span><br><span class="line">0xc000012088 </span><br><span class="line">0xc000012088 </span><br></pre></td></tr></table></figure>
<p>这里其实就可以看出来了，<code>&amp;stu</code> 指向了同一个内存地址，当遍历到最后一个元素时，将3写入了该地址。导致映射所有值都相同。<code>for range</code> 创建了每个元素的副本，而不是直接返回每个元素的引用，如果使用该值变量的地址作为指向每个元素的指针，就会导致错误，迭代时返回的变量是一个迭代过程中根据切片依次赋值的新变量，所以值的地址总是相同的，导致结果不如预期。</p>
<p>修改代码：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">exercises02Test</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="built_in">make</span> := <span class="built_in">make</span>(<span class="keyword">map</span>[<span class="type">int</span>]*<span class="type">int</span>)</span><br><span class="line">	slice := []<span class="type">int</span>&#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;</span><br><span class="line">	<span class="keyword">for</span> index, value := <span class="keyword">range</span> slice &#123;</span><br><span class="line">		<span class="comment">// 循环中使用新的变量接收</span></span><br><span class="line">		item := value</span><br><span class="line">		fmt.Printf(<span class="string">&quot;%p \n&quot;</span>, &amp;item)</span><br><span class="line">		<span class="built_in">make</span>[index] = &amp;item</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> k, v := <span class="keyword">range</span> <span class="built_in">make</span> &#123;</span><br><span class="line">		fmt.Println(k, <span class="string">&quot;=&gt;&quot;</span>, *v)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">0xc000012088 </span><br><span class="line">0xc0000120c0 </span><br><span class="line">0xc0000120c8</span><br><span class="line">0xc0000120d0</span><br><span class="line">3 =&gt; 3</span><br><span class="line">0 =&gt; 0</span><br><span class="line">1 =&gt; 1</span><br><span class="line">2 =&gt; 2</span><br></pre></td></tr></table></figure>
<p>这个问题很像C#学习委托时遇到的闭包问题。上面问题还可以使用传统的 <code>for</code> 循环处理：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">exercises03Test</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="built_in">make</span> := <span class="built_in">make</span>(<span class="keyword">map</span>[<span class="type">int</span>]*<span class="type">int</span>)</span><br><span class="line">	slice := []<span class="type">int</span>&#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;</span><br><span class="line">	<span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="built_in">len</span>(slice); i++ &#123;</span><br><span class="line">		<span class="built_in">make</span>[i] = &amp;slice[i]</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> k, v := <span class="keyword">range</span> <span class="built_in">make</span> &#123;</span><br><span class="line">		fmt.Println(k, <span class="string">&quot;=&gt;&quot;</span>, *v)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">0xc0000101e0 </span><br><span class="line">0xc0000101e8 </span><br><span class="line">0xc0000101f0 </span><br><span class="line">0xc0000101f8 </span><br><span class="line">0 =&gt; 0       </span><br><span class="line">1 =&gt; 1       </span><br><span class="line">2 =&gt; 2       </span><br><span class="line">3 =&gt; 3  </span><br></pre></td></tr></table></figure>
<h1 id="练习题二">练习题二</h1>
<p>因为 <code>slice</code> 和 <code>map</code> 这两种数据类型都包含了指向底层数据的指针，因此在需要复制它们时要特别注意。来看下面的例子：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Test <span class="keyword">struct</span> &#123;</span><br><span class="line">	name   <span class="type">string</span></span><br><span class="line">	age    <span class="type">int8</span></span><br><span class="line">	dreams []<span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t *Test)</span></span> setDreams(dreams []<span class="type">string</span>) &#123;</span><br><span class="line">	t.dreams = dreams</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">exercises02Test</span><span class="params">()</span></span> &#123;</span><br><span class="line">	t := Test&#123;name: <span class="string">&quot;wangpengliang&quot;</span>, age: <span class="number">18</span>&#125;</span><br><span class="line">	data := []<span class="type">string</span>&#123;<span class="string">&quot;吃饭&quot;</span>, <span class="string">&quot;睡觉&quot;</span>, <span class="string">&quot;搞钱&quot;</span>&#125;</span><br><span class="line">	t.setDreams(data)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 真的想修改t.dreams吗？</span></span><br><span class="line">	data[<span class="number">1</span>] = <span class="string">&quot;不睡觉&quot;</span></span><br><span class="line">	fmt.Println(t.dreams) <span class="comment">// </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[吃饭 不睡觉 搞钱]</span><br></pre></td></tr></table></figure>
<p>这里因为 <code>slice</code> 和 <code>map</code> 这两种数据类型都包含了指向底层数据的指针所以修改了 <code>slice</code> 导致结构体内容也被修改，正确做法应该是：方法中使用传入的slice的拷贝进行结构体赋值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t *Test)</span></span> setDreams(dreams []<span class="type">string</span>) &#123;</span><br><span class="line">	t.dreams = <span class="built_in">make</span>([]<span class="type">string</span>, <span class="built_in">len</span>(dreams))</span><br><span class="line">	<span class="built_in">copy</span>(t.dreams, dreams)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">t := Test&#123;name: <span class="string">&quot;wangpengliang&quot;</span>, age: <span class="number">18</span>&#125;</span><br><span class="line">data := []<span class="type">string</span>&#123;<span class="string">&quot;吃饭&quot;</span>, <span class="string">&quot;睡觉&quot;</span>, <span class="string">&quot;搞钱&quot;</span>&#125;</span><br><span class="line">t.setDreams(data)</span><br><span class="line"></span><br><span class="line">data[<span class="number">1</span>] = <span class="string">&quot;不睡觉&quot;</span></span><br><span class="line">fmt.Println(t.dreams) </span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[吃饭 睡觉 搞钱]</span><br></pre></td></tr></table></figure>

</div>


  <div class="book-comments">
    




  </div>



<script src="/js/book-post.js"></script>

        </div>
      </div>
      <div class="column col-2 hide-lg">
        <div class="book-post-info">
  
    <div class="book-post-meta">

  <div class="author">

    <!-- Author image -->
    <div class="author-img">
      
        <figure
          class="avatar avatar-lg"
          data-initial="W"
          style="background-color: #3b4351;">
        </figure>
      
    </div>

    <!-- Author title -->
    <div class="author-title">
      <div>WangPengLiang</div>
      <div>2022-03-30</div>
    </div>
  </div>

  

  <div class="divider"></div>
</div>
  

  <div class="book-tocbot">
</div>
<div class="book-tocbot-menu">
  <a class="book-toc-expand" onclick="expand_toc()">Expand all</a>
  <a onclick="go_top()">Back to top</a>
  <a onclick="go_bottom()">Go to bottom</a>
</div>


<script src="/js/book-toc.js"></script>

</div>
      </div>
    </div>
  </div>
  
  <a class="off-canvas-overlay" onclick="hide_canvas()"></a>
</div>

</body>
</html>


<script src="/js/book.js"></script>
